package com.lanyou.cook.service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.datadictionary.UserLogOpt;
import com.lanyou.cook.entity.domain.UserLog;
import com.lanyou.cook.repository.UserLogRepository;
import com.lanyou.cook.util.SpringWebUtil;

@Service
public class UserLogService implements ApplicationContextAware {

	private static ApplicationContext applicationContext;
	
	@Autowired
	private UserLogRepository userLogRepository;
	
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		UserLogService.applicationContext = applicationContext;
	}
	
	public static UserLogService getInstance(){
		return applicationContext.getBean(UserLogService.class);
	}
	
	@Transactional
	public void save(UserLogOpt optType, String operatorUserCode, String contents){
		UserLog userLog = new UserLog();
		userLog.setOptType(optType.ValueCode);
		userLog.setContents(contents);
		userLog.setOptTime(new Date());
		
		if(operatorUserCode == null){
			Subject subject = SecurityUtils.getSubject();
			if(subject.isAuthenticated()){
				List principals = subject.getPrincipals().asList();
				if(principals.size() == 1){
					userLog.setUserCode((String)principals.get(0));
					userLog.setOptPerson((String)principals.get(0));
				}else{
					userLog.setUserCode((String)principals.get(0));
					userLog.setOptPerson((String)principals.get(1));
				}
			}
		} else {
			userLog.setUserCode(operatorUserCode);
			userLog.setOptPerson(operatorUserCode);
		}
		
		// 保证帐号名和姓名不为空
		if(userLog.getUserCode() == null){
			userLog.setUserCode(Constants.APPLICATION_NAME);
		}
		if(userLog.getOptPerson() == null){
			userLog.setOptPerson(Constants.APPLICATION_NAME2);
		}

		HttpServletRequest req = SpringWebUtil.getCurrentRequest();
		if(req != null){
			userLog.setLoginIp(req.getRemoteAddr());
		}
		
		userLogRepository.save(Arrays.asList(userLog));
	}
}